﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Simhopp.Common
{
    public static class DiveMap
    {
        /// <summary>
        /// Saves a dive to the database
        /// </summary>
        /// <param name="dive">The dive to be saved</param>
        /// <returns>The index of the inserted/updated row</returns>
        public static int SaveDiveToDatabase(Dive dive)
        {
            int id = GenericMap.SaveObjectToDatabase(dive);
            foreach (var score in dive.Scores)
                ScoreMap.SaveScoreToDatabase(score);
            return id;
        }

        /// <summary>
        /// Reads all the dives for one diver from the database
        /// </summary>
        /// <param name="diverId">Id of the current diver</param>
        /// <returns>A list of dives</returns>
        public static List<Dive> ReadAllDivesForOneDiver(int diverId)
        {
            var diveList =
                MyDbConnection.ReadFromTable(String.Format(@"select * from Dives where DiverId='{0}'", diverId))
                    .Select(Dive.GetFromDictionary)
                    .ToList();
            MyLogger.Debug(String.Format("Dives for diver {0} loaded from database", diverId));
            return diveList;
        }

        public static void RemoveDiveFromDatabase(Dive dive)
        {
            foreach (var score in dive.Scores)
                ScoreMap.RemoveScoreFromDatabase(score);
            GenericMap.RemoveObjectFromDatabase(dive);
        }

        public static List<Dive> ReadAllDivesFromDatabase()
        {
            var dictionary = GenericMap.ReadAllObjectsFromDatabase(typeof(Dive));
            try
            {
                var dives = dictionary.Select(Dive.GetFromDictionary).ToList();
                MyLogger.Debug("All dictionaries converted to Dive-objects");
                return dives;
            }
            catch (Exception e)
            {
                MyLogger.Error("Could not convert all dictionaries to Dive-objects - " + e.Message);
                return null;
            }
        }

        public static Dive ReadDiveFromDatabase(int id)
        {
            var dbResult = GenericMap.ReadObjectFromDatabase(id, typeof(Dive));
            return dbResult == null ? null : Dive.GetFromDictionary(dbResult);
        }
    }
}
